<template>
    <div class="roles">
    <!-- 添加 -->
        <el-button type="primary" @click="addForm[0].show = true">添加角色</el-button>
        <Dialog :dialog="addForm">
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addForm[0].show = false">取消</el-button> 
                    <el-button type="primary" @click="add">确定</el-button>
                </span>
            </template>
        </Dialog>
    <!-- 表格 -->
        <Table switch parent :data="rolesData" :cols="cols">
            <template #expand="scope">
                <el-row class="box" v-for="(item, index) in scope.row.children" :key="index">
                    <el-col :span="6" class="cent">
                        <el-tag class="big" closable @close="delrights(item.id,scope.row)">{{item.authName}}</el-tag>
                    </el-col>
                    <el-col :span="18">
                    <el-row class="box"  v-for="(it, indexs) in item.children" :key="indexs">
                        <el-col :span="6" >
                        <el-tag class="big" closable @close="delrights(it.id,scope.row)" type="success">{{it.authName}}</el-tag>
                        </el-col>
                        <el-col :span="18" >
                        <el-tag closable v-for="(its, ins) in it.children" @close="delrights(its.id,scope.row)" :key="ins" type="warning">{{its.authName}}</el-tag>
                        </el-col>
                    </el-row>
                    </el-col>
                </el-row>
            </template>
            <template #action="scope">
                <el-button type="primary" @click="open(scope.row)" :icon="Edit" circle />
                 <el-button type="danger" @click="del(scope.row)" :icon="Delete" circle />
                 <el-button type="warning" @click="Open(scope.row)" :icon="Setting" circle />
            </template>
        </Table>
        <!-- {{rids}} -->
        <!-- 修改角色 -->
         <Dialog :dialog="changeForm">
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="changeForm[0].show = false">取消</el-button> 
                    <el-button type="primary" @click="changed">确定</el-button>
                </span>
            </template>
        </Dialog>
        <!-- 权限管理 -->
         <Dialog :dialog="rolesForm">
             <template #right>
                 <div class="box2">
                     <el-tree
                     ref="treeRef"
                    :data="rightsData"
                    show-checkbox
                    default-expand-all
                    node-key="id"
                    highlight-current
                    :props="props"
                    @check-change="Checked"
                    :default-expanded-keys="checkedId"
                    :default-checked-keys="checkedId"
                />
                 </div>
             </template>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="esc">取消</el-button> 
                    <el-button type="primary" @click="got">确定</el-button>
                </span>
            </template>
        </Dialog>
    </div>
</template>
<script setup>
import Dialog from '@/components/Dialog.vue'
import Table from '@/components/Table.vue'
import { onMounted,ref,getCurrentInstance } from 'vue'
import {  Edit, Delete, Setting } from "@element-plus/icons-vue";
import { ElMessage,ElMessageBox,ElTree } from 'element-plus'
// import type Node from 'element-plus/es/components/tree/src/model/node'
import { getRoles,addRoles,changeRoles,delRoles,setRights,delRights } from '@/utils/roles.js'
import { getRights } from '@/utils/rights.js'
const { proxy } = getCurrentInstance();
// 添加表单
const addForm = ref([
    {
        show:false,
        title:'添加角色',
        data:ref([
            {
                name:'名称',
                prop:'roleName',
                value:'',
                placeholder:'该项不可为空'
            },
            {
                name:'描述',
                prop:'roleDesc',
                value:'',
            }
        ])
    },
    {   
        slot:'footer',
    }
])
// 修改表单
const changeForm = ref([
    {
        show:false,
        title:'修改角色',
        data:ref([
            {
                hide:true,
                prop:'id',
                value:''
            },
            {
                name:'名称',
                prop:'roleName',
                value:'',
                placeholder:'该项不可为空'
            },
            {
                name:'描述',
                prop:'roleDesc',
                value:'',
            }
        ])
    },
    {   
        slot:'footer',
    }
])
// 权限管理
const rolesForm = ref([
    {
        show:false,
        title:'分配权限',
    },
    {
        slot:'right'
    },
    {
        slot:'footer',
    }
])
// 权限
const props = {label:'authName',children:'children'}
// 权限列表
const rightsData = ref([])
// 列
const cols = ref([
    {
        slot:'expand',
        type:'expand',
        title:'',
        align:'center'
    },
    {
        type:'index',
        title:'',
        align:'center',
        width:60
    },
    {
        name:'roleName',
        title:'角色',
        align:'center',
    },
    {
        name:'roleDesc',
        title:'描述',
        align:'center',
    },
    {
        slot:'action',
        title:'操作',
        align:'center',
    }
])
// 表格
const rolesData = ref([]);
// 添加
const add = async ()=>{
    var form = {}; 
    addForm.value[0].data.map(item=>{
        // return `${item.prop}:${item.value}`
        return form[item.prop] = item.value
    })
     if(form.roleName == ''){
        return ElMessage.warning('角色名称不能为空');
    }
    console.log(form);
    let data = await addRoles(form);
     if(data.meta.status == 201){
        ElMessage.success(data.meta.msg);
        addForm.value[0].show = false;
    }
    getRolesList();
    console.log(data,'添加')
}
//修改按钮
const open = (row)=>{              
    changeForm.value[0].show = true;
    changeForm.value[0].data.forEach(item=>{
        item.prop,Object.keys(row).forEach((it,i)=>{
            if(item.prop == it){
                item.value = Object.values(row)[i];
            }
        })
    });
}
// 修改
const changed = async()=>{
    var form = {}; 
    changeForm.value[0].data.map(item=>{
        return form[item.prop] = item.value
    })
    // console.log(form,885)
    let data = await changeRoles(form.id,form);
    // console.log(data,'修改')
    if(data.meta.status == 200){
        ElMessage.success(data.meta.msg);
        changeForm.value[0].show = false;
        getRolesList();
    }
}
// 删除权限
const delrights = async (id,row)=>{
    // console.log(id,row.id)
    let data = await delRights(row.id,id);
    if( data.meta.status == 200 ){
        ElMessage.success(data.meta.msg);
        var index = rolesData.value.findIndex(item=>{
            return item.id == row.id;
        })
        rolesData.value[index].children = data.data;
    }
}
// 删除
const del = async (row)=>{
    console.log(row)
    ElMessageBox.confirm(
    `您确认删除【${row.roleName}】吗？删除后无法恢复`,
    '删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
        var data = await delRoles(row.id)
      ElMessage({
        type: 'success',
        message: data.meta.msg,
      })
      getRolesList();
    }).catch(() => {})
}
const checkedId = ref([])
// 角色id
const roleId = ref('');
//角色按钮
const Open = async (row)=>{              
    rolesForm.value[0].show = true;
    roleId.value = row.id;
    let {data:res} = await getRights('tree');
    rightsData.value = res;
    // 回显
    let arr = [];
    function fn (role){
        role.forEach(item=>{
            if(item.children){
                fn(item.children);
            }else{
               return arr.push(item.id);
            }
        })
    }
    fn(row.children);
    checkedId.value = arr;
    proxy.$refs.treeRef.setChecked(checkedId.value,true,false);
}
// 权限
const got = async ()=>{
    let data = await setRights(roleId.value,rids.value.join(','))
    if(data.meta.status == 200){
        rolesForm.value[0].show = false;
        ElMessage.success(data.meta.msg);
        getRolesList();
        localStorage.setItem('rids', JSON.stringify(rids.value));
    }
}
// 权限id
const rids = ref([]);
const Checked = ()=>{
    let id =[...proxy.$refs.treeRef.getCheckedNodes(),...proxy.$refs.treeRef.getHalfCheckedNodes()];
    rids.value = id.map(item=>item.id);
}
// 取消
const esc = ()=>{
    rolesForm.value[0].show = false;
    rids.value = [];
}
// 渲染
const getRolesList = async () =>{
    let {data:res} = await getRoles();
    rolesData.value = res;
}
onMounted(() => {
    getRolesList();  
    rids.value = JSON.parse(localStorage.getItem('rids'));
})
</script>
<style lang="scss" scoped>
    .el-tag{
        margin: 5px 10px;
    }
    .box{
        padding: 20px 0;
        border-bottom: 1px solid rgb(233, 232, 232);
    }
    .box:last-of-type{
        border: none;
    }
    .box2{
        height: 500px;
        overflow: auto;
        width: 100%;
    }
    ::-webkit-scrollbar {
        display: none; 
    }
    .cent{
        position: relative;
        .big{
            
        position: absolute;
        top: 50%;
        left: 35px;
        transform: translate(0,-50%);
        }
    }
</style>